package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/6/15 21:40
 */
@Controller
@Slf4j
public class HelloController
{
    @RequestMapping({"/", "/index"})
    public String toIndex(Model model)
    {
        model.addAttribute("msg", "hello");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add()
    {
        return "/user/add";
    }

    @RequestMapping("/user/update")
    public String update()
    {
        return "/user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin()
    {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password,boolean checkbox)
    {
        String saltPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("加密后的密码是：{}",saltPassword);
        log.info("CheckBox：{}",checkbox);
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        log.info("token:{}",token);
        if(checkbox){
            token.setRememberMe(true);
        }
        log.info("remember me:{}",subject.isRemembered());
        log.info("auth:{}",subject.isAuthenticated());
        try
        {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e)
        {
            e.printStackTrace();
            return "login";
        }
    }

    @RequestMapping("/unAuthorized")
    @ResponseBody
    public String unAuthorized()
    {
        return "未经授权无法访问此页面！";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletResponse resp)
    {
        //得到当前 Subject
        Subject currentSubject = SecurityUtils.getSubject();
        //注销当前 Subject
        currentSubject.logout();
        resp.setStatus(302);
        return "redirect:login";
    }
}



